package com.qifan.energy.util.pay;

import android.app.Activity;

import com.qifan.energy.bean.result.PayOrderWechatResult;
import com.qifan.energy.bean.vo.GenerateOrderParamVO;
import com.qifan.energy.BuildConfig;
import com.qifan.energy.bean.result.GenerateOrderResult;
import com.qifan.energy.http.net.NetUtils;
import com.qifan.energy.http.response.MyObserver;
import com.qifan.energy.util.ToastUtils;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

/**
 * Created by 傅令杰
 */

public class FastPayUtil {

    //设置支付回调监听
    private IAlPayResultListener mIAlPayResultListener = null;
    private Activity mActivity = null;

    /*private AlertDialog mDialog = null;*/
    /*private int mOrderID = -1;*/

    private FastPayUtil(Activity activity) {
        this.mActivity = activity;
        /*this.mDialog = new AlertDialog.Builder(activity.getApplicationContext()).create();*/
    }

    public static FastPayUtil create(Activity activity) {
        return new FastPayUtil(activity);
    }

    /*public void beginPayDialog() {
        mDialog.show();
        final Window window = mDialog.getWindow();
        if (window != null) {
            window.setContentView(R.layout.dialog_pay_panel);
            window.setGravity(Gravity.BOTTOM);
            window.setWindowAnimations(R.style.anim_panel_up_from_bottom);
            window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            //设置属性
            final WindowManager.LayoutParams params = window.getAttributes();
            params.width = WindowManager.LayoutParams.MATCH_PARENT;
            params.flags = WindowManager.LayoutParams.FLAG_DIM_BEHIND;
            window.setAttributes(params);

            window.findViewById(R.id.btn_dialog_pay_alpay).setOnClickListener(this);
            window.findViewById(R.id.btn_dialog_pay_wechat).setOnClickListener(this);
            window.findViewById(R.id.btn_dialog_pay_cancel).setOnClickListener(this);
        }
    }*/

    public FastPayUtil setPayResultListener(IAlPayResultListener listener) {
        this.mIAlPayResultListener = listener;
        return this;
    }

    /*public FastPayUtil setOrderId(int orderId) {
        this.mOrderID = orderId;
        return this;
    }*/

    /* 发起支付宝支付 */
    public void alPay(int orderId) {
        //1.生成订单
        GenerateOrderParamVO orderParamVO = new GenerateOrderParamVO();
        orderParamVO.setMemberReceiveAddressId(12);
        orderParamVO.setPayType(1);
        NetUtils.orderGenerateOrder(orderParamVO ,new MyObserver<GenerateOrderResult>(mActivity) {

            @Override
            public void onSuccess(GenerateOrderResult result) {
                //2.拉起支付宝SDK 必须是异步的调用客户端支付接口
                /*final PayAsyncTask payAsyncTask = new PayAsyncTask(mActivity, mIAlPayResultListener);
                payAsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, result.getAlipayOrderStr());*/
            }

            @Override
            public void onFailure(Throwable e, String errorMsg) {
                ToastUtils.showShort(errorMsg);
            }
        });
    }

    /* 发起微信支付 */
    private void weChatPay(int orderId) {
        /*LatteLoader.stopLoading();
        final String weChatPrePayUrl = "你的服务端微信预支付地址" + orderId;
        LatteLogger.d("WX_PAY", weChatPrePayUrl);

        final IWXAPI iwxapi = LatteWeChat.getInstance().getWXAPI();
        final String appId = Latte.getConfiguration(ConfigKeys.WE_CHAT_APP_ID);
        iwxapi.registerApp(appId);
        RestClient.builder()
                .url(weChatPrePayUrl)
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        final JSONObject result =
                                JSON.parseObject(response).getJSONObject("result");
                        final String prepayId = result.getString("prepayid");
                        final String partnerId = result.getString("partnerid");
                        final String packageValue = result.getString("package");
                        final String timestamp = result.getString("timestamp");
                        final String nonceStr = result.getString("noncestr");
                        final String paySign = result.getString("sign");

                        final PayReq payReq = new PayReq();
                        payReq.appId = appId;
                        payReq.prepayId = prepayId;
                        payReq.partnerId = partnerId;
                        payReq.packageValue = packageValue;
                        payReq.timeStamp = timestamp;
                        payReq.nonceStr = nonceStr;
                        payReq.sign = paySign;

                        iwxapi.sendReq(payReq);
                    }
                })
                .build()
                .post();*/
    }

    /**
     * 调支付的方法
     * 注意： 每次调用微信支付的时候都会校验 appid 、包名 和 应用签名的。 这三个必须保持一致才能够成功调起微信
     * @param result
     */
    public void startWechatPay(PayOrderWechatResult result) {

        ToastUtils.showShort("调起微信支付....");
        //这里的appid，替换成自己的即可
        IWXAPI api = WXAPIFactory.createWXAPI(this.mActivity, BuildConfig.WX_APPKEY,true);
        api.registerApp(BuildConfig.WX_APPKEY);

        //这里的bean，是服务器返回的json生成的bean
        PayReq payRequest = new PayReq();
        payRequest.appId = result.getAppid();
        payRequest.partnerId = result.getPartnerid();
        payRequest.prepayId = result.getPrepayid();
        payRequest.packageValue = result.getPackageValue();//固定值
        payRequest.nonceStr = result.getNoncestr();
        payRequest.timeStamp = result.getTimestamp();
        payRequest.sign = result.getSign();
        payRequest.signType = result.getSignType();

        //发起请求，调起微信前去支付
        api.sendReq(payRequest);
    }
}
